package demo.api.impl;

import demo.api.CtmsService;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.io.IOException;
import java.util.List;

/**
 * Created by rock on 17/3/29.
 */
public class CtmsServiceImpl implements CtmsService {

    private Retrofit retrofit;
    private String token;

    private CtmsServiceImpl() {}

    public CtmsServiceImpl(String url) {
        this.retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public Dto.CtmsResponse createOrder(List<Dto.OrderEntity> orderEntities) throws IOException {
        Call<CtmsService.Dto.CtmsResponse> responseCall =
                retrofit.create(RestApi.class).createOrder(token,
                        Dto.OrderRequest.builder().orderList(orderEntities).build());
        final Response<CtmsService.Dto.CtmsResponse> response = responseCall.execute();
        if( !response.isSuccessful() ) {
            return Dto.CtmsResponse.create(response);
        }

        return response.body();
    }

    @Override
    public Dto.CtmsResponse cancelOrders(List<String> numbers) throws IOException {
        Call<CtmsService.Dto.CtmsResponse> responseCall =
                retrofit.create(RestApi.class).cancelOrders(token,
                        Dto.CancelOrderRequest.builder().numbers(numbers).build());
        final Response<CtmsService.Dto.CtmsResponse> response = responseCall.execute();
        if( !response.isSuccessful() ) {
            return Dto.CtmsResponse.create(response);
        }

        return response.body();
    }

    public Dto.CtmsResponse updateBatch(List<Dto.OrderEntity> orderEntities) throws IOException {
        Call<CtmsService.Dto.CtmsResponse> responseCall =
                retrofit.create(RestApi.class).updateBatch(token,
                        Dto.OrderRequest.builder().orderList(orderEntities).build());
        final Response<CtmsService.Dto.CtmsResponse> response = responseCall.execute();
        if( !response.isSuccessful() ) {
            return Dto.CtmsResponse.create(response);
        }

        return response.body();
    }

    @Override
    public void authorize(String token) {
        this.token = token;
    }

}
